<template>
  <div class="app-container">
    <div class="canvas-container">
      <div v-if="!callback"
          class="canvas"
          :style="{ width: formData.width + 'px', height: formData.height + 'px', border: '1px solid #000' }"
          @mousedown="startDrag"
          @mouseup="stopDrag"
          @mousemove="drag"
      >
        <div
            v-for="(item,name) in itemMap"
            :key="name"
            :class="['item', item.type]"
            :style="getItemStyle(item)"
            @mousedown="startItemDrag(item, $event)"
            @mouseup="stopItemDrag(item, $event)"
            @mousemove="dragItem"
        >
          <div v-if="item.type === 'text'" v-text="item.vvv.value" :title="item.vvv.title"
               :style="getTextStyle(item)" />
          <img v-if="item.type === 'image'" :src="item.vvv.value" :title="item.vvv.title"
               :style="{ width: item.ppp.width + 'px', height: item.ppp.height + 'px' }" />
        </div>
      </div>
      <div v-else
           class="canvas"
           :style="{ width: formData.width + 'px', height: formData.height + 'px', border: '1px solid #000' }"
      >
        <img :src="previewImage">
      </div>
    </div>
    <div class="form-data">
      <div>
        <el-button type="success" size="mini" @click="submitConfig">保 存</el-button>
        <el-checkbox v-if="false" v-model="callback" style="font-size: 12px; margin-left: 10px" >后端预览</el-checkbox>
        <span style="font-size: 12px; color: #409EFF;margin-left: 10px">修改模板名称可以另存为新的模板</span>
      </div>
      <div>
        <el-divider content-position="left">基本设置</el-divider>
        <el-form ref="baseForm" :model="formData" size="mini"
                 :rules="baseRules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="模板名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入模板名称,修改名称可以新名称保存" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="抬头名称" prop="title">
                <el-input v-model="formData.title" placeholder="请输入抬头名称,标签显示名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="溯源网址" prop="webSite">
                <el-input v-model="formData.webSite" placeholder="请输入溯源网址，id变量放最后" />
              </el-form-item>
            </el-col>
            <el-col :span="12" style="display: inline-flex">
              <el-form-item label="标签尺寸" prop="width">
                <el-input-number v-model="formData.width" controls-position="right" :min="10" :step="5"  style="width: 75px"/> x
                <el-input-number v-model="formData.height" controls-position="right" :min="10" :step="5" style="width: 75px"/> mm
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider content-position="left">显示排版</el-divider>
        <el-form ref="titleForm" :model="formData" size="mini"
                 :rules="titleRules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="抬头定位" prop="name">
                x: <el-input-number v-model="formData.titlePos.x" controls-position="right" :min="0" :step="1" style="width: 70px"/>,
                y: <el-input-number v-model="formData.titlePos.y" controls-position="right" :min="0" :step="1" style="width: 70px"/>  (mm)
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="尺寸大小" prop="position">
                <el-input-number v-model="formData.titlePos.width" controls-position="right" :min="10" :step="1"  style="width: 75px"/> x
                <el-input-number v-model="formData.titlePos.height" controls-position="right" :min="10" :step="1" style="width: 75px"/> (mm)
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="字体设置" prop="style">
                font:<el-input v-model="formData.titleStyle.fontName" placeholder="请输入字体名称"  style="width: 80px"/>
                size:<el-input-number v-model="formData.titleStyle.fontSize" controls-position="right" :min="8" :step="1" style="width: 70px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示间距" prop="style">
                间距:<el-input-number v-model="formData.titleStyle.space" controls-position="right" :min="0.00" :step="0.05" :max="1.00" :precision="2" style="width: 70px"/>
                行高:<el-input-number v-model="formData.titleStyle.lineHeight" controls-position="right" :min="8" :step="1" style="width: 70px"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="二 维 码" prop="name">
                x: <el-input-number v-model="formData.qrCodePos.x" controls-position="right" :min="0" :step="1" style="width: 70px"/>,
                y: <el-input-number v-model="formData.qrCodePos.y" controls-position="right" :min="0" :step="1" style="width: 70px"/>  (mm)
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="尺寸大小" prop="position">
                <el-input-number v-model="formData.qrCodePos.width" controls-position="right" :min="10" :step="1"  style="width: 75px"/> x
                <el-input-number v-model="formData.qrCodePos.height" controls-position="right" :min="10" :step="1" style="width: 75px"/> (mm)
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="条 形 码" prop="name">
                x: <el-input-number v-model="formData.barCodePos.x" controls-position="right" :min="-20" :step="1" style="width: 70px"/>,
                y: <el-input-number v-model="formData.barCodePos.y" controls-position="right" :min="0" :step="1" style="width: 70px"/>  (mm)
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="尺寸大小" prop="position">
                <el-input-number v-model="formData.barCodePos.width" controls-position="right" :min="10" :step="1"  style="width: 75px"/> x
                <el-input-number v-model="formData.barCodePos.height" controls-position="right" :min="10" :step="1" style="width: 75px"/> (mm)
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="数码字体" prop="style">
                font:<el-input v-model="formData.barCodeStyle.fontName" placeholder="请输入字体名称"  style="width: 80px"/>
                size:<el-input-number v-model="formData.barCodeStyle.fontSize" controls-position="right" :min="8" :step="1" style="width: 70px"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {previewConfig, saveConfig} from '@/api/config'
import qrCodeImg from '@/assets/image/qrCode.png';
import barCodeImg from '@/assets/image/barCode.png';

export default {
  name: 'Canvas',
  props:{
    callback:{
      type:Boolean,
      default: false
    },
    formData:{
      type: Object,
      default:()=>{
        return {
          width: 240,
          height: 240,
          title: '',
          webSite: ''
        };
      }
    }
  },
  data() {
    return {
      loading: null,
      itemMap: {},
      draggingItem: null,
      dragging: false,
      dragStart: { x: 0, y: 0 },
      itemDragStart: { x: 0, y: 0 },
      previewImage: null,
      baseRules:{

      },
      titleRules:{

      },
      imageRules:{

      }
    };
  },
  watch:{
    formData:{
      handler(newData, oldData) {
        if(this.itemMap.titleItem) {
          this.refresh();
        }
      },
      deep: true,
      immediate: true // 立即执行
    }
  },
  created(){
    this.init();
  },
  methods: {
    openLoading(){
      if(this.loading) this.loading.close();
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    init(){
      this.itemMap= {
        titleItem: {
          type: 'text',
          vvv: {
            value: '四字名称',
            title: '抬头名称',
          },
          ppp: {
            x: 5, // Initial position
            y: 5,  // Initial position
            width: 110, // Initial width for image box
            height: 110, // Initial height for image box
          },
          sss:{
            fonFamily: '宋体',
            fontSize: 42,
            space: 0.10,
            lineHeight: 50
          }
        },
        qrCodeItem: {
          type: 'image',
          vvv: {
            value: qrCodeImg,
            title: '二维码',
          },
          ppp:{
            x: 110, // Initial position
            y: 5,  // Initial position
            width: 136, // Initial width for image box
            height: 136, // Initial height for image box
          }
        },
        barCodeItem: {
          type: 'image',
          vvv: {
            value: barCodeImg,
            title: '条形码',
          },
          ppp:{
            x: 5, // Initial position
            y: 155,  // Initial position
            width: 235, // Initial width for image box
            height: 65, // Initial height for image box
          }
        },
        barNumItem: {
          type: 'text',
          vvv: {
            value: '987654321012',
            title: '数码值',
          },
          ppp:{
            x: 5, // Initial position
            y: 205,  // Initial position
            width: 235, // Initial width for image box
            height: 35, // Initial height for image box
          },
          sss:{
            fonFamily: '宋体',
            fontSize: 42,
            space: 0.0,
            lineHeight: 50
          }
        }
      }
    },
    refresh(){
      this.openLoading()
      if(!this.callback){
        this.itemMap.titleItem.vvv.value = this.formData.title;
        if(this.formData.titleStyle){
          let ts = this.formData.titleStyle;
          this.itemMap.titleItem.sss = ts;
        }


        if(this.formData.titlePos){
          let tp = this.formData.titlePos;
          this.itemMap.titleItem.ppp = tp;
        }
        if(this.formData.qrCodePos){
          let tp = this.formData.qrCodePos;
          this.itemMap.qrCodeItem.ppp = tp;
        }
        if(this.formData.barCodePos){
          let tp = this.formData.barCodePos;
          this.itemMap.barCodeItem.ppp = tp;

          this.itemMap.barNumItem.ppp = {
            x: tp.x,
            y: tp.y + tp.height,
            width: tp.width,
            height: 35
          };
        }

        if(this.formData.barCodeStyle){
          let ts = this.formData.barCodeStyle;
          this.itemMap.barNumItem.sss = ts;
        }

        if(this.loading){
          this.loading.close();
          this.loading = null;
        }
      }else{
        previewConfig(this.formData).then(rsp=>{
          var imgData = rsp.preview ? "data:image/png;base64," + rsp.preview : null;
          this.previewImage = imgData;
          if(this.loading){
            this.loading.close();
            this.loading = null;
          }
        },reject=>{
          if(this.loading){
            this.loading.close();
            this.loading = null;
          }
        });
      }
      //console.log(this.itemMap)
    },
    startDrag(event) {
      // Handle canvas dragging (optional)
    },
    stopDrag() {
      // Handle canvas dragging stop (optional)
    },
    drag(event) {
      // Handle canvas dragging (optional)
    },
    startItemDrag(item, event) {
      this.draggingItem = item;
      this.dragging = true;
      this.itemDragStart = { x: event.clientX - item.left, y: event.clientY - item.top };
      event.stopPropagation();
    },
    stopItemDrag(item, event) {
      this.dragging = false;
      this.draggingItem = null;
      event.stopPropagation();
    },
    dragItem(event) {
      if (this.dragging && this.draggingItem) {
        this.draggingItem.ppp.x = event.clientX - this.itemDragStart.x;
        this.draggingItem.ppp.y = event.clientY - this.itemDragStart.y;
      }
      event.stopPropagation();
    },
    getItemStyle(item) {
      return {
        position: 'absolute',
        left: `${item.ppp.x}px`,
        top: `${item.ppp.y}px`,
      };
    },
    getTextStyle(item){
      var sss = {width: item.ppp.width + 'px', height: item.ppp.height + 'px',};

      if(item.sss){
        sss.fontFamily = item.sss.fontName;
        sss.fontSize = item.sss.fontSize + 'px';
        if(item.sss.lineHeight) {
          sss.lineHeight = item.sss.lineHeight + 'px'
        }
        if(item.sss.space) {
          sss.letterSpacing = item.sss.space;
        }
      }

      return sss;
    },
    submitConfig(){
      saveConfig(this.formData).then(response => {
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        this.$emit('ok');
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.app-container{
  width: 100%;
  display: inline-block;

::v-deep  .canvas-container {
    position: relative;
    display: inline-flex;
    flex-direction: column;
    width: 40%;
    min-width: 300px;
    height: 300px;
    overflow: auto;
    text-align: center;
    background-image: linear-gradient(45deg, #f5f5f5 25%, transparent 0, transparent 75%, #f5f5f5 0), linear-gradient(45deg, #f5f5f5 25%, transparent 0, transparent 75%, #f5f5f5 0);
    background-position: 0 0, 13px 13px;
    background-size: 26px 26px;

    .canvas {
      position: relative;
      overflow: hidden;

      margin: 25px auto;
      transform-origin: center top;
      box-shadow: 0 0 5px 1px #ccc;
      background-color: #fff;
      background-repeat: no-repeat;
    }

    .item {
      border: 1px solid #ccc;
      padding: 0 0;
      background: #fff;
      resize: both;
      overflow: auto;
      box-sizing: border-box;
    }

    .controls {
      margin-top: 10px;
    }
  }

  .form-data{
    width: 60%;
    float: right;

    .el-divider--horizontal{
      margin: 12px 0;
      .el-divider__text {
        font-weight: bold;
      }
    }

    .el-form-item__label{
      font-weight: bold;
    }
  }
}

::v-deep .el-input-number.is-controls-right .el-input__inner{
  padding-left: 5px;
  padding-right: 40px;
}
</style>
